/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sirafia;

import com.sun.data.provider.RowKey;
import com.sun.data.provider.impl.CachedRowSetDataProvider;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.sql.rowset.CachedRowSetXImpl;
import com.sun.webui.jsf.component.Button;
import com.sun.webui.jsf.component.Checkbox;
import com.sun.webui.jsf.component.Label;
import com.sun.webui.jsf.component.PanelLayout;
import com.sun.webui.jsf.component.RadioButton;
import com.sun.webui.jsf.component.TableColumn;
import com.sun.webui.jsf.component.TableRowGroup;
import com.sun.webui.jsf.component.TextArea;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.event.TableSelectPhaseListener;
import com.sun.webui.jsf.model.DefaultTableDataProvider;
import com.sun.webui.jsf.model.SingleSelectOptionsList;
import java.beans.Statement;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.DateTimeConverter;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporter;
import sirafia_clases.Conexion;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version consultaAgendasporNumero.java
 * @version Created on 06-10-2012, 08:37:55 PM
 * @author Esparta86
 */

public class consultaAgendasporNumero extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        dropDown1DefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("item1", "XX ----------- 60 -----------XX"), new com.sun.webui.jsf.model.Option("item2", "JD dia/mes/a\u00f1o - dia/mes/a\u00f1o"), new com.sun.webui.jsf.model.Option("item3", "JD dia/mes/a\u00f1o - dia/mes/a\u00f1o"), new com.sun.webui.jsf.model.Option("item4", "JD dia/mes/a\u00f1o - dia/mes/a\u00f1o")});
        agendaDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{consultaAgendasporNumero.agendaRowSet}"));
        agendaRowSet.setDataSourceName("java:comp/env/jdbc/sirafia_PostgreSQL");
        agendaRowSet.setCommand("SELECT ALL sirafia.agenda.agendanumero, to_char(sirafia.agenda.fechasesag,'DD/MM/YYYY') as fechasesag  FROM sirafia.agenda  ORDER BY sirafia.agenda.fechasesag DESC");
        //agendaRowSet.setCommand("SELECT *  FROM sirafia.agenda");
        agendaRowSet.setTableName("agenda");

        


    }
    private DefaultTableDataProvider defaultTableDataProvider = new DefaultTableDataProvider();

    public DefaultTableDataProvider getDefaultTableDataProvider() {
        return defaultTableDataProvider;
    }

    public void setDefaultTableDataProvider(DefaultTableDataProvider dtdp) {
        this.defaultTableDataProvider = dtdp;
    }
    private DateTimeConverter dateTimeConverter1 = new DateTimeConverter();

    public DateTimeConverter getDateTimeConverter1() {
        return dateTimeConverter1;
    }

    public void setDateTimeConverter1(DateTimeConverter dtc) {
        this.dateTimeConverter1 = dtc;
    }
    private SingleSelectOptionsList dropDown1DefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDropDown1DefaultOptions() {
        return dropDown1DefaultOptions;
    }

    public void setDropDown1DefaultOptions(SingleSelectOptionsList ssol) {
        this.dropDown1DefaultOptions = ssol;
    }
    private TextField txtAnio = new TextField();

    public TextField getTxtAnio() {
        return txtAnio;
    }

    public void setTxtAnio(TextField tf) {
        this.txtAnio = tf;
    }
    private Label msjError1 = new Label();

    public Label getMsjError1() {
        return msjError1;
    }

    public void setMsjError1(Label l) {
        this.msjError1 = l;
    }
    private PanelLayout layoutPanelAgendaAnio = new PanelLayout();

    public PanelLayout getLayoutPanelAgendaAnio() {
        return layoutPanelAgendaAnio;
    }

    public void setLayoutPanelAgendaAnio(PanelLayout pl) {
        this.layoutPanelAgendaAnio = pl;
    }
    private CachedRowSetDataProvider agendaDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getAgendaDataProvider() {
        return agendaDataProvider;
    }

    public void setAgendaDataProvider(CachedRowSetDataProvider crsdp) {
        this.agendaDataProvider = crsdp;
    }
    private CachedRowSetXImpl agendaRowSet = new CachedRowSetXImpl();

    public CachedRowSetXImpl getAgendaRowSet() {
        return agendaRowSet;
    }

    public void setAgendaRowSet(CachedRowSetXImpl crsxi) {
        this.agendaRowSet = crsxi;
    }
    private TableRowGroup tableRowGroup2 = new TableRowGroup();

    public TableRowGroup getTableRowGroup2() {
        return tableRowGroup2;
    }

    public void setTableRowGroup2(TableRowGroup trg) {
        this.tableRowGroup2 = trg;
    }
    private Button btnImprimirAgendaAnio1 = new Button();

    public Button getBtnImprimirAgendaAnio1() {
        return btnImprimirAgendaAnio1;
    }

    public void setBtnImprimirAgendaAnio1(Button b) {
        this.btnImprimirAgendaAnio1 = b;
    }
    private RadioButton radioButton1 = new RadioButton();

    public RadioButton getRadioButton1() {
        return radioButton1;
    }

    public void setRadioButton1(RadioButton rb) {
        this.radioButton1 = rb;
    }
    private TableColumn tableColumn5 = new TableColumn();

    public TableColumn getTableColumn5() {
        return tableColumn5;
    }

    public void setTableColumn5(TableColumn tc) {
        this.tableColumn5 = tc;
    }

    // </editor-fold>

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public consultaAgendasporNumero() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    
    //private boolean DoneConsultaAnio = false;
    

    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("consultaAgendasporNumero Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
        /*if(this.DoneConsultaAnio){

        }*/

    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
        agendaDataProvider.close();
    }

/*Seleccionar una o varias filas de una tabla*/
    private TableSelectPhaseListener tablePhaseListener = new TableSelectPhaseListener();

    public void setSelected(Object object) {
       RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
       if (rowKey != null) {
           tablePhaseListener.setSelected(rowKey, object);
       }
   }

   public Object getSelected(){
       RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
       return tablePhaseListener.getSelected(rowKey);

   }

   public Object getSelectedValue() {
       RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
       return (rowKey != null) ? rowKey.getRowId() : null;

   }

   public boolean getSelectedState() {
       RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
       return tablePhaseListener.isSelected(rowKey);
   }

  /**Termina para seleccionar varias filas*/


   protected SessionBean1 getSessionBean1() { return (SessionBean1) getBean("SessionBean1"); }
   
    


    public String tab3_action() {
        // TODO: Replace with your code
        return null;
    }

    public String tab5_action() {
        // TODO: Replace with your code
        return null;
    }

    public String imageHyperlink1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
/*
          try {
            // TODO: Process the action. Return value is a navigation
            // case name where null will return to the same page.
            generarReporte(1);
        } catch (SQLException ex) {
            Logger.getLogger(consultaAgendasporNumero.class.getName()).log(Level.SEVERE, null, ex);

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(consultaAgendasporNumero.class.getName()).log(Level.SEVERE, null, ex);
        }

*/
        return null;
    }


    public String tab1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String btnBuscarAgendaAnio_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        int anio = 0;
        try {
                anio = Integer.parseInt("" + txtAnio.getText());
                if (anio < 0) {
                    msjError1.setText("Digite en un formato de 4 valores numericos el año, ej. 2000");
                } else {
                    //Eecutar consulta
                    String sql="SELECT ALL sirafia.agenda.agendanumero, to_char(sirafia.agenda.fechasesag,'DD/MM/YYYY') as fechasesag, sirafia.agenda.diragenda  FROM sirafia.agenda where sirafia.agenda.anioagenda="+anio+" ORDER BY sirafia.agenda.fechasesag DESC ";
                    //agendaDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.agendaRowSet}"));
                   //agendaDataProvider1.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{consultaAgendasporNumero.agendaRowSet}"));
                   agendaRowSet.setDataSourceName("java:comp/env/jdbc/sirafia_PostgreSQL");
                   agendaRowSet.setCommand(sql);
                   agendaRowSet.setTableName("agenda");
                   agendaDataProvider.refresh();


                    layoutPanelAgendaAnio.setVisible(true);
            }
                }catch (Exception e) {
                msjError1.setText("El año debe ser un valor numerico");
                layoutPanelAgendaAnio.setVisible(false);
            }


        return null;
    }

    public String button4_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String btnImprimirAgendaAnio1_action() throws Exception {
        //this.DoneConsultaAnio=true;
        

        String cadena="";
        String cadena2[];
        
        int selectedRows = getTableRowGroup2().getSelectedRowsCount();
        cadena=cadena+"rows "+selectedRows+":: ";
        RowKey[] selectedRowKeys =getTableRowGroup2().getSelectedRowKeys();
        cadena2=new String[selectedRowKeys.length];
        for(int i=0; i< selectedRowKeys.length; i++){
            
            try {
            agendaDataProvider.setCursorRow(selectedRowKeys[i]);
            
            cadena2[i]=agendaDataProvider.getValue("agendanumero").toString();
            }catch(Exception e){
             msjError1.setText("no se pudo recuperar el recurso");
            }
            
        }
        msjError1.setText(": "+cadena);
        String salida="";
      /*
        for(int i=0;i<cadena2.length;i++){
        salida=salida+"\n  "+cadena2[i];
        }*/
 

        if(cadena2.length >0){//Si se selecciono al menos un documento

        
          
          
         try{

          PreparedStatement st=Conexion.conector().prepareStatement("SELECT diragenda FROM sirafia.agenda WHERE agendanumero=?");
          st.setString(1, cadena2[0]);
          ResultSet rs=st.executeQuery();
          String pathAgenda="";
          while(rs.next()){
             pathAgenda=rs.getString(1);
             }
          rs.close();
          st.close();
           
            getSessionBean1().guardarPathAgenda(pathAgenda);//Guardo los documentos que selecciono
            getSessionBean1().guardarNombreDocumento("Agenda");
         
            }
          catch(SQLException ex){
       //Mas adelante manjear correctamente el error
          }

            return "notificarS";
        }// termina if de verificacion de selecciono documento
    
        

       


        return null;
    }

    public String tab2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String imageHyperlink2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button12_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button5_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button6_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String imageHyperlink3_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button13_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String tab4_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button7_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button8_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String imageHyperlink4_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button14_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button9_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button10_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String imageHyperlink5_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String button15_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public void txtAnio_processValueChange(ValueChangeEvent vce) {
    }


    public void checkbox1_processValueChange(ValueChangeEvent event) {
           btnImprimirAgendaAnio1.setVisible(true);

    }


    
}

